package com.yuyu.qingmangmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.yuyu.common.constant.ProductConstant;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.qingmangmall.product.dao.AttrAttrgroupRelationDao;
import com.yuyu.qingmangmall.product.dao.AttrDao;
import com.yuyu.qingmangmall.product.dao.AttrGroupDao;
import com.yuyu.qingmangmall.product.dao.CategoryDao;
import com.yuyu.qingmangmall.product.entity.AttrAttrgroupRelationEntity;
import com.yuyu.qingmangmall.product.entity.AttrEntity;
import com.yuyu.qingmangmall.product.entity.AttrGroupEntity;
import com.yuyu.qingmangmall.product.entity.CategoryEntity;
import com.yuyu.qingmangmall.product.service.AttrService;
import com.yuyu.qingmangmall.product.service.CategoryService;
import com.yuyu.qingmangmall.product.vo.AttrRespVo;
import com.yuyu.qingmangmall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();

        // BeanUtils： Spring 提供的工具类
        BeanUtils.copyProperties(attr,attrEntity);  // .copyProperties方法可以将两个类相同属性，从一个类复制到另一个类

        // 保存基本数据
        this.save(attrEntity);

        if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            // 基本属性下 保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());

            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    @Transactional
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(attrType)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        String key = (String) params.get("key");
        // 模糊查询
        if (!StringUtils.isNullOrEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        // 根据三级分类显示规格参数列表
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id",catelogId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils((page));

        //  设置 三级分类的名字和分组名字
        List<Object> attr_id = page.getRecords().stream().map((attrEntity) -> {
            AttrRespVo respVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, respVo);

            // 设置 三级分类的名字
            CategoryEntity category = categoryDao.selectById(attrEntity.getCatelogId());

            if (category != null) {
                respVo.setCatelogName(category.getName());
            }


            // 基本属性下 设置分组名字
//            Long attrId = attrEntity.getAttrId();
            if ("base".equalsIgnoreCase(attrType)) {  // 只有在查询规格参数时才设置分组
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                        .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));

                if (relationEntity != null && relationEntity.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroup = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    respVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }

            return respVo;
        }).collect(Collectors.toList());


        pageUtils.setList(attr_id);

        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo respVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,respVo);

        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 基本属性下 拿到分组名
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                    .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrEntity.getAttrId()));

            if (relationEntity!=null){
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (groupEntity!=null){
                    respVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
        }


        // 拿到分类完整路径
        Long catelogId = attrEntity.getCatelogId();

       if (catelogId!=null){
           // .findCatelogPath()方法可以递归拿到父Id
           Long[] catelogPath = categoryService.findCatelogPath(catelogId);

           respVo.setCatelogPath(catelogPath);
       }


        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);

        // 修改基本数据
        this.updateById(attrEntity);

        // 基本属性下 修改关联关系
        if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){

            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));

            if (count>0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }

        }



    }

    /**
     * 根据分组Id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntity = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id",attrgroupId));

        List<Long> attrIdList = relationEntity.stream().map((attr) -> {
            Long attrId = attr.getAttrId();
            return attrId;
        }).collect(Collectors.toList());

        if (attrIdList == null || attrIdList.size()==0){
            return null;
        }
        List<AttrEntity> attrEntityList = this.listByIds(attrIdList);
        return attrEntityList;
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getRelationNoAttr(Map<String, Object> params, Long attrgroupId) {
        // 1.当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 2.当前分组只能关联别的分组没有引用的属性
        // 2.1 当前分类下的其他分组
        List<AttrGroupEntity> catelog_id = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 2.2 这些分组关联的属性
        List<Long> attrGroupIdList = catelog_id.stream().map(item -> {
            Long attrGroupId = item.getAttrGroupId();

            return attrGroupId;
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIdList));

        List<Long> attrIdList = relationEntityList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        // 2.3 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIdList!=null && attrIdList.size()>0) {
            wrapper.notIn("attr_id", attrIdList);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)){
            wrapper.and((queryWrapper)->{
                queryWrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    /**
     * 过滤出searchType为1的attrId
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> getSearchAttrIds(List<Long> attrIds) {

        return baseMapper.selectBatchIdsBySearchTypeAndAttrId(attrIds);
    }

}